from sqlalchemy.orm import Session
from sqlalchemy import and_, or_, desc
from typing import List, Dict, Any, Optional

from app.models.merchant import Merchant, MerchantImage
from app.models.user import User
from app.schemas.merchant import MerchantCreate, MerchantUpdate, MerchantImageCreate


def get_merchant(db: Session, merchant_id: int) -> Optional[Merchant]:
    """根据ID获取商家"""
    return db.query(Merchant).filter(
        Merchant.id == merchant_id,
        Merchant.is_deleted == False
    ).first()


def get_merchant_by_user_id(db: Session, user_id: int) -> Optional[Merchant]:
    """根据用户ID获取商家"""
    return db.query(Merchant).filter(
        Merchant.user_id == user_id,
        Merchant.is_deleted == False
    ).first()


def get_merchants(
    db: Session, 
    skip: int = 0, 
    limit: int = 100,
    name: Optional[str] = None,
    is_verified: Optional[bool] = None,
    is_active: Optional[bool] = None
) -> List[Merchant]:
    """获取商家列表，支持筛选"""
    query = db.query(Merchant).filter(Merchant.is_deleted == False)
    
    if name:
        query = query.filter(Merchant.name.ilike(f"%{name}%"))
    
    if is_verified is not None:
        query = query.filter(Merchant.is_verified == is_verified)
    
    if is_active is not None:
        query = query.filter(Merchant.is_active == is_active)
    
    return query.order_by(desc(Merchant.created_at)).offset(skip).limit(limit).all()


def create_merchant(db: Session, merchant: MerchantCreate, user_id: int) -> Merchant:
    """创建商家"""
    db_merchant = Merchant(
        **merchant.dict(),
        user_id=user_id
    )
    db.add(db_merchant)
    db.commit()
    db.refresh(db_merchant)
    
    # 更新用户角色
    user = db.query(User).filter(User.id == user_id).first()
    if user:
        user.role = "merchant"
        db.commit()
    
    return db_merchant


def update_merchant(
    db: Session, 
    merchant_id: int, 
    merchant_update: MerchantUpdate
) -> Optional[Merchant]:
    """更新商家信息"""
    db_merchant = get_merchant(db, merchant_id)
    if not db_merchant:
        return None
    
    # 更新商家信息
    update_data = merchant_update.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_merchant, key, value)
    
    db.commit()
    db.refresh(db_merchant)
    return db_merchant


def delete_merchant(db: Session, merchant_id: int) -> bool:
    """删除商家（软删除）"""
    db_merchant = get_merchant(db, merchant_id)
    if not db_merchant:
        return False
    
    db_merchant.is_deleted = True
    db_merchant.is_active = False
    db.commit()
    return True


def verify_merchant(db: Session, merchant_id: int, is_verified: bool) -> Optional[Merchant]:
    """验证/取消验证商家"""
    db_merchant = get_merchant(db, merchant_id)
    if not db_merchant:
        return None
    
    db_merchant.is_verified = is_verified
    db.commit()
    db.refresh(db_merchant)
    return db_merchant


def create_merchant_image(
    db: Session, 
    merchant_id: int, 
    image: MerchantImageCreate
) -> Optional[MerchantImage]:
    """添加商家图片"""
    # 检查商家是否存在
    db_merchant = get_merchant(db, merchant_id)
    if not db_merchant:
        return None
    
    # 如果是封面图，先将所有其他图片设为非封面
    if image.is_cover:
        db.query(MerchantImage).filter(
            MerchantImage.merchant_id == merchant_id,
            MerchantImage.is_cover == True
        ).update({"is_cover": False})
    
    # 创建图片
    db_image = MerchantImage(
        **image.dict(),
        merchant_id=merchant_id
    )
    db.add(db_image)
    db.commit()
    db.refresh(db_image)
    return db_image


def delete_merchant_image(db: Session, image_id: int) -> bool:
    """删除商家图片"""
    db_image = db.query(MerchantImage).filter(MerchantImage.id == image_id).first()
    if not db_image:
        return False
    
    db.delete(db_image)
    db.commit()
    return True 